package com.jsn.controller;

import com.jsn.exception.SmartWebResponseExceptionTranslator;
import com.jsn.support.BaseController;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.token.TokenService;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


//@RestController
//@AllArgsConstructor
public class OAuth2Controller extends BaseController {

    @Lazy
    private TokenStore tokenStore;

    private AccessTokenConverter accessTokenConverter;
    private SmartWebResponseExceptionTranslator smartWebResponseExceptionTranslator;


    @RequestMapping({"/oauth/check_token"})
    @ResponseBody
    public Map<String, ?> checkToken(@RequestParam("token") String value) {
        try {
            OAuth2AccessToken token = tokenStore.readAccessToken(value);
            if (token == null) {
                throw new InvalidTokenException("Token was not recognised");
            } else if (token.isExpired()) {
                throw new InvalidTokenException("Token has expired");
            } else {
                OAuth2Authentication authentication = tokenStore.readAuthentication(token.getValue());
//            OAuth2Authentication authentication = defaultTokenServices.loadAuthentication(token.getValue());
                Map<String, Object> response = (Map<String, Object>) this.accessTokenConverter.convertAccessToken(token, authentication);
                response.put("active", true);
                System.out.println("自定义checkToken！！！");
                return response;
            }
        } catch (Exception e) {

            smartWebResponseExceptionTranslator.translate(e);
        }
        return null;
    }

}
